import aiohttp
import requests
import lxml.html
import random
import time
import re
import urllib
from faker import Faker

def get_ts():
    return str(time.time()).replace('.', '')[:13]


async def get_qrcode(usertel, amount):

    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        'CLIENT-IP': ip,
        'X-FORWARDED-FOR': ip,
    }
    async with aiohttp.ClientSession(headers=headers) as session:
        url = 'http://gd.189.cn/dwr/exec/WebPayCommonDwr.queryCityName.dwr'
        tel_param = 'string:' + usertel
        # 'c0-id': '424_1534148880466',
        data = {'c0-id': '1496_1534154416873',
                'c0-methodName': 'queryCityName',
                'c0-param0': 'boolean:false',
                'c0-param1': 'boolean:false',
                'c0-param2': tel_param,
                'c0-scriptName': 'WebPayCommonDwr',
                'callCount': '1',
                'xml': 'true'}

        orderid = lambda: str(round(random.random() * 10001)) + '_' + str(time.time()).replace('.', '')[:13]
        data['c0-id'] = orderid()
        async with session.post(url, data=data) as rsp:
            content = await rsp.text()
            city_code = re.findall('s1="(\d+)"', content)
            if city_code:
                city_code = "string:%s" % city_code[0]
            else:
                return None

        data = {'c0-id': orderid(),
                'c0-methodName': 'getNumberBalance',
                'c0-param0': 'boolean:false',
                'c0-param1': 'boolean:false',
                'c0-param2': city_code,
                'c0-param3': tel_param,
                'c0-param4': 'string:CDMA',
                'c0-param5': 'string:5BC',
                'c0-scriptName': 'WebPayCommonDwr',
                'callCount': '1',
                'xml': 'true'}
        url = 'http://gd.189.cn/dwr/exec/WebPayCommonDwr.getNumberBalance.dwr'
        async with session.post(url, data=data) as rsp:
            content = await rsp.text()
            print(content)
    # url = 'http://gd.189.cn/webpay/chongzhi/newchargeinfo.html'
    # s.get(url)
    #
    # url = 'http://gd.189.cn/webpay/chongzhi/newincharge.html'
    # s.get(url)
    # url = 'http://gd.189.cn/webpay/chongzhi/newzfbsmpay.html'
    # s.get(url)
    # url = 'http://gd.189.cn/webpay/chongzhi/czselect4alipayScan.jsp?ffchinapay=100&realpay=99.8&LateFeeV=0&Order_url='
    # s.get(url)
        url = 'http://gd.189.cn/ChongzhiOrder.do'
        pay_fee = int(amount) * 0.995
        data = {'LateFeeV': '0',
                'Order_source': 'WEB',
                'ffchinapay': amount,
                'payfee': str(pay_fee),
                'selectedBankType': 'alipayScan'}
        print(data)
        async with session.post(url, data=data) as rsp:
            content = await rsp.text()

            root = lxml.html.fromstring(content)
            eles = root.xpath('//input')
            data = {e.name: e.value for e in eles}
         print(data)
        async with session.post(url, data=data) as rsp:
            content = await rsp.text()
            root = lxml.html.fromstring(content)

        url = root.xpath('//form/@action')[0]
        async with session.post(url) as rsp:
            content = await rsp.text()
            ctoken = session.cookies['ctoken']
            print(ctoken)

            root = lxml.html.fromstring(rsp.content.decode('gbk'))
            qrcode = root.xpath('//input[@name="qrCode"]/@value')

            pay_orderid = urllib.parse.urlparse(rsp.url).query
            pay_orderid = dict(urllib.parse.parse_qsl(pay_orderid))

            data = {'_': get_ts(),
                    '_input_charset': 'utf-8',
                    'ctoken': ctoken,
                    'payOrderId': pay_orderid['payOrderId']}
            url = 'https://excashier.alipay.com/standard/queryQRStatus.json'
            rsp = s.get(url, params=data)
            print(rsp.url)
            print(rsp.content)
            return qrcode


print(get_qrcode('18122730927', '200'))
# data = dict(orderId=orderId, bankCode=bankCode, paymentCode=paymentCode)
# rsp = s.post(url, data=data)
# root = lxml.html.document_fromstring(rsp.content.decode())
# eles = root.xpath('//form/input')
#
# ele = root.xpath('//form')
# url2 = ele[0].action
# # url2 = 'http://paygo.189.cn:9778/189pay/service'
# rsp = s.post(url2, data=data)
# data = {}
# for e in eles:
#     data[e.name] = e.value
# rsp = s.post(url2, data=data)
# root = lxml.html.document_fromstring(rsp.content.decode())
# eles = root.xpath('//form/input')
# data = {}
#
# for e in eles:
#     data[e.name] = e.value
#
# ele = root.xpath('//form')
# url2 = ele[0].action
# # url2 = 'https://mapi.alipay.com/gateway.do?_input_charset=utf-8'
# rsp = s.post(url2, data=data)
# root = lxml.html.document_fromstring(rsp.content.decode('gbk'))
# ele = root.xpath('//input[@name="qrCode"]')
# qrcode = ele[0].value
# url = 'http://www.189.cn/trade/payment/pay.do'
